/**
 * 
 */
package stc.skymobi.ebus.unit;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import stc.skymobi.ebus.EventBus;
import bsh.Interpreter;


/**
 * @author hp
 *
 */
public class BshEventUnitImpl implements EventUnit, UnitSourceAware {

	 private static final Logger logger = 
		 LoggerFactory.getLogger(BshEventUnitImpl.class);
	
    private UnitSource	source;
    private	EventUnit	impl;
    
    public BshEventUnitImpl() {
    }
    
    /* (non-Javadoc)
     * @see com.skymobi.ebus.unit.EventUnit#init(com.skymobi.ebus.EventBus)
     */
//    @Override
	public Object init(EventBus eventBus) {
    	if ( logger.isDebugEnabled() ) {
    		logger.debug("current thread contextClassLoader {}", 
    				Thread.currentThread().getContextClassLoader());
    	}
    	
    	 Interpreter inter = new Interpreter();
         
    	 try {
			impl = (EventUnit)inter.eval( 
					 IOUtils.toString( source.getInputStream(), "UTF-8") );
		} catch (Exception e) {
    		logger.error("failed in init bsh EventUnit: {}", e);
    		return	null;
		} 

		if ( null != impl ) {
			return	impl.init(eventBus);
		}
		else {
			return	null;
		}
    }

    /* (non-Javadoc)
     * @see com.skymobi.ebus.unit.EventUnit#destroy(java.lang.Object)
     */
//    @Override
    public void destroy(Object ctx) {
    	if ( null != this.impl ) {
    		this.impl.destroy(ctx);
    		this.impl = null;
    	}
    }

    /* (non-Javadoc)
     * @see com.skymobi.ebus.unit.EventUnit#getDescription()
     */
//    @Override
    public String getDescription() {
        return source.getName();
    }

	public void setUnitSource(UnitSource source) {
		this.source = source;
	}

}
